// 学习进度记录与间隔重复算法实现

// 定义学习进度数据结构
const ProgressData = {
    // 存储每个句子的学习记录
    sentenceRecords: {},
    
    // 存储每个单词的学习记录
    wordRecords: {},
    
    // 存储总积分
    score: 0,
    
    // 存储当前学习进度
    currentSentenceIndex: 0,
    currentWordIndexInSentence: 0,
    
    // 存储单词学习开始时间
    wordLearningStartTime: null,
    
    // 初始化进度数据
    init() {
        const savedData = localStorage.getItem('englishLearningProgress');
        if (savedData) {
            try {
                const parsedData = JSON.parse(savedData);
                this.sentenceRecords = parsedData.sentenceRecords || {};
                this.wordRecords = parsedData.wordRecords || {};
                this.score = parsedData.score || 0;
                this.currentSentenceIndex = parsedData.currentSentenceIndex || 0;
                this.currentWordIndexInSentence = parsedData.currentWordIndexInSentence || 0;
            } catch (e) {
                console.error('Failed to parse saved progress data:', e);
                this.reset();
            }
        } else {
            this.reset();
        }
    },
    
    // 重置进度数据
    reset() {
        this.sentenceRecords = {};
        this.wordRecords = {};
        this.score = 0;
        this.currentSentenceIndex = 0;
        this.currentWordIndexInSentence = 0;
        this.save();
    },
    
    // 保存进度数据到localStorage
    save() {
        localStorage.setItem('englishLearningProgress', JSON.stringify({
            sentenceRecords: this.sentenceRecords,
            wordRecords: this.wordRecords,
            score: this.score,
            currentSentenceIndex: this.currentSentenceIndex,
            currentWordIndexInSentence: this.currentWordIndexInSentence
        }));
    },
    
    // 开始单词学习计时
    startWordLearning(word) {
        this.wordLearningStartTime = Date.now();
    },
    
    // 结束单词学习并记录时长
    finishWordLearning(word, isCorrect) {
        if (this.wordLearningStartTime === null) return;
        
        const now = Date.now();
        const learningDuration = now - this.wordLearningStartTime; // 毫秒
        this.wordLearningStartTime = null;
        
        let record = this.wordRecords[word] || {
            word: word,
            level: 0,         // 掌握级别 0-5
            nextReview: 0,    // 下次复习时间戳
            lastReviewed: 0,  // 上次复习时间戳
            consecutiveCorrect: 0, // 连续正确次数
            totalAttempts: 0, // 总尝试次数
            correctAttempts: 0, // 正确尝试次数
            totalLearningTime: 0 // 总学习时长(毫秒)
        };
        
        record.totalAttempts++;
        record.totalLearningTime += learningDuration;
        
        if (isCorrect) {
            record.correctAttempts++;
            record.consecutiveCorrect++;
            
            // 根据连续正确次数提升级别
            if (record.consecutiveCorrect >= 3 && record.level < 5) {
                record.level++;
                record.consecutiveCorrect = 0;
            }
        } else {
            record.consecutiveCorrect = 0;
            // 级别下降或保持不变
            if (record.level > 0) {
                record.level = Math.max(0, record.level - 1);
            }
        }
        
        record.lastReviewed = now;
        // 根据级别计算下次复习时间
        record.nextReview = this.calculateNextReviewTime(record.level, now);
        
        this.wordRecords[word] = record;
        this.save();
    },
    
    // 更新积分
    updateScore(points) {
        this.score += points;
        this.save();
    },
    
    // 获取当前积分
    getScore() {
        return this.score;
    },
    
    // 更新句子学习记录
    updateSentenceRecord(sentenceId, isCorrect) {
        const now = Date.now();
        let record = this.sentenceRecords[sentenceId] || {
            id: sentenceId,
            level: 0,         // 掌握级别 0-5
            nextReview: 0,    // 下次复习时间戳
            lastReviewed: 0,  // 上次复习时间戳
            consecutiveCorrect: 0, // 连续正确次数
            totalAttempts: 0, // 总尝试次数
            correctAttempts: 0 // 正确尝试次数
        };
        
        record.totalAttempts++;
        if (isCorrect) {
            record.correctAttempts++;
            record.consecutiveCorrect++;
            
            // 根据连续正确次数提升级别
            if (record.consecutiveCorrect >= 3 && record.level < 5) {
                record.level++;
                record.consecutiveCorrect = 0;
            }
        } else {
            record.consecutiveCorrect = 0;
            // 级别下降或保持不变
            if (record.level > 0) {
                record.level = Math.max(0, record.level - 1);
            }
        }
        
        record.lastReviewed = now;
        // 根据级别计算下次复习时间 (间隔重复算法)
        record.nextReview = this.calculateNextReviewTime(record.level, now);
        
        this.sentenceRecords[sentenceId] = record;
        this.save();
    },
    
    // 计算下次复习时间
    calculateNextReviewTime(level, currentTime) {
        // 间隔天数根据级别递增
        const intervals = [1, 3, 7, 14, 30, 60]; // 级别0-5对应的天数
        const days = intervals[Math.min(level, intervals.length - 1)];
        return currentTime + (days * 24 * 60 * 60 * 1000);
    },
    
    // 获取需要复习的句子ID列表
    getSentencesToReview() {
        const now = Date.now();
        return Object.values(this.sentenceRecords)
            .filter(record => record.nextReview <= now)
            .sort((a, b) => a.nextReview - b.nextReview)
            .map(record => record.id);
    },
    
    // 获取句子的掌握程度
    getSentenceMastery(sentenceId) {
        const record = this.sentenceRecords[sentenceId];
        if (!record) return 0;
        return record.level / 5; // 0-1之间的值
    },
    
    // 设置当前学习进度
    setCurrentProgress(sentenceIndex, wordIndex) {
        this.currentSentenceIndex = sentenceIndex;
        this.currentWordIndexInSentence = wordIndex;
        this.save();
    },
    
    // 获取当前学习进度
    getCurrentProgress() {
        return {
            sentenceIndex: this.currentSentenceIndex,
            wordIndex: this.currentWordIndexInSentence
        };
    },
    
    // 重置当前学习进度
    resetCurrentProgress() {
        this.currentSentenceIndex = 0;
        this.currentWordIndexInSentence = 0;
        this.save();
    }
};

// 初始化进度数据
ProgressData.init();

// 打印下次复习的数据
ProgressData.logNextReviewData = function() {
    console.log('===== 下次复习数据 =====');
    
    // 打印句子复习数据
    console.log('\n句子复习数据:');
    const allSentenceRecords = Object.values(this.sentenceRecords);
    
    if (allSentenceRecords.length === 0) {
        console.log('暂无学习记录');
    } else {
        const sentenceRecordsWithNextReview = allSentenceRecords
            .filter(record => record.nextReview > 0)
            .sort((a, b) => a.nextReview - b.nextReview);
        
        if (sentenceRecordsWithNextReview.length === 0) {
            console.log('暂无需要复习的句子');
        } else {
            sentenceRecordsWithNextReview.forEach(record => {
                const nextReviewDate = new Date(record.nextReview);
                const now = new Date();
                const timeDiff = record.nextReview - now.getTime();
                const daysRemaining = Math.ceil(timeDiff / (24 * 60 * 60 * 1000));
                
                console.log(`句子 ID: ${record.id}`);
                console.log(`掌握级别: ${record.level}/5`);
                console.log(`下次复习时间: ${nextReviewDate.toLocaleString()}`);
                console.log(`剩余天数: ${daysRemaining > 0 ? daysRemaining + ' 天' : '今天'}`);
                console.log('------------------------');
            });
        }
    }
    
    // 打印单词复习数据
    console.log('\n单词复习数据:');
    // 检查wordRecords是否存在
    if (typeof this.wordRecords === 'undefined' || Object.keys(this.wordRecords).length === 0) {
        console.log('暂无单词学习记录');
    } else {
        const allWordRecords = Object.values(this.wordRecords);
        
        const wordRecordsWithNextReview = allWordRecords
            .filter(record => record.nextReview > 0)
            .sort((a, b) => a.nextReview - b.nextReview);
        
        if (wordRecordsWithNextReview.length === 0) {
            console.log('暂无需要复习的单词');
        } else {
            wordRecordsWithNextReview.forEach(record => {
                const nextReviewDate = new Date(record.nextReview);
                const now = new Date();
                const timeDiff = record.nextReview - now.getTime();
                const daysRemaining = Math.ceil(timeDiff / (24 * 60 * 60 * 1000));
                const avgLearningTime = Math.round(record.totalLearningTime / record.totalAttempts / 1000); // 秒
                
                console.log(`单词: ${record.word}`);
                console.log(`掌握级别: ${record.level}/5`);
                console.log(`下次复习时间: ${nextReviewDate.toLocaleString()}`);
                console.log(`剩余天数: ${daysRemaining > 0 ? daysRemaining + ' 天' : '今天'}`);
                console.log(`平均学习时长: ${avgLearningTime} 秒`);
                console.log('------------------------');
            });
        }
    }
    console.log('===== 下次复习数据 =====');
};

// 初始化后自动打印下次复习数据
ProgressData.logNextReviewData();

// 导出进度数据对象
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ProgressData;
}